package com.swn.common.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

/**
 * http请求封装工具类
 * 
 * @author 陶召才
 * @Date 2016年4月14日  下午5:33:27
 * @Note <这里是该类的使用注意事项>
 *
 * TODO
 *

 */
public class HttpClientUtil {  
  
	private static HttpClientUtil instance;
	public HttpClientUtil(){}
	
	public static HttpClientUtil getDefault(){
		synchronized(HttpClientUtil.class){
			if(null == instance){
				instance = new HttpClientUtil();
			}
			return instance;
		}
	}
    /**
     * 通过get方式调用请求地址
     * 
     * @author 陶召才
     * @Date 2016年4月14日  下午5:26:28
     * @Note <这里是使用注意事项>
     *
     * @param url
     * @param nameValuePairList：List<NameValuePair>
     * @return
     * @throws Exception
     *
     * @return String
     */
    public static String get(String url, List<NameValuePair> nameValuePairList) throws Exception {  
        String body = null;  
        try {  
        	HttpClient httpClient = new DefaultHttpClient(); 
            // Get请求  
            HttpGet httpget = new HttpGet(url);  
            // 设置参数  
            String str = EntityUtils.toString(new UrlEncodedFormEntity(nameValuePairList));  
            httpget.setURI(new URI(httpget.getURI().toString() + "?" + str));  
            // 发送请求  
            HttpResponse httpresponse = httpClient.execute(httpget);  
            // 获取返回数据  
            HttpEntity entity = httpresponse.getEntity();  
            body = EntityUtils.toString(entity);  
            if (entity != null) {  
                entity.consumeContent();  
            }  
        }  catch (Exception e) {  
            throw new Exception(e);  
        }  
        return body;  
    } 
    
    
    
    
    
    
    
    
    /**
     * 通过post方式调用请求地址
     * 
     * @author 陶召才
     * @Date 2016年4月14日  下午5:27:38
     * @Note <这里是使用注意事项>
     *
     * @param url
     * @param nameValuePairList:List<NameValuePair>
     * @return
     *
     * @return String
     */
    public static String post(String url,List<NameValuePair> nameValuePairList){
    	StringBuffer responseStr = new StringBuffer();
    	
		HttpPost httpPost = null;
		HttpEntity he = null; 
		HttpClient hc = null;
		InputStream is  = null;
		BufferedReader br = null;
		try { 
			hc = new DefaultHttpClient();
			httpPost = new HttpPost(url);
	    
			he = new UrlEncodedFormEntity(nameValuePairList, "UTF-8");
			httpPost.setEntity(he); 
			
			HttpResponse ht = hc.execute(httpPost);
			
			//连接成功
			if(ht.getStatusLine().getStatusCode() == HttpStatus.SC_OK){ 	
				HttpEntity het = ht.getEntity();
			    is = het.getContent();
				br = new BufferedReader(new InputStreamReader(is,"UTF-8"));
				String readLine = null;
				while((readLine =br.readLine()) != null){ 
					responseStr.append(readLine);
				}
			}else{
				responseStr.append("返回失败！");
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}finally{
			if(is!=null)
				try {
					is.close();
				} catch (IOException e) {
					throw new RuntimeException(e);
				}
			if(br!=null)
				try {
					br.close();
				} catch (IOException e) {
					throw new RuntimeException(e);
				}
		}
		return responseStr.toString();
	}
      
  
    /**
     * 发送 Post请求 (有待测试)
     * 
     * @author 陶召才
     * @Date 2016年4月14日  下午5:28:34
     * @Note <这里是使用注意事项>
     *
     * @param url
     * @param reqXml
     * @return
     * @throws Exception
     *
     * @return String
     */
    public static String post(String url, String reqXml) throws Exception {  
        String body = null;  
        HttpClient httpClient = new DefaultHttpClient(); 
        try {  
            //设置客户端编码  
            httpClient.getParams().setParameter("http.protocol.content-charset",HTTP.UTF_8);  
            httpClient.getParams().setParameter(HTTP.CONTENT_ENCODING, HTTP.UTF_8);  
            httpClient.getParams().setParameter(HTTP.CHARSET_PARAM, HTTP.UTF_8);  
            httpClient.getParams().setParameter(HTTP.DEFAULT_PROTOCOL_CHARSET,HTTP.UTF_8);  
            // Post请求  
            HttpPost httppost = new HttpPost(url);  
            //设置post编码  
            httppost.getParams().setParameter("http.protocol.content-charset",HTTP.UTF_8);  
            httppost.getParams().setParameter(HTTP.CONTENT_ENCODING, HTTP.UTF_8);  
            httppost.getParams().setParameter(HTTP.CHARSET_PARAM, HTTP.UTF_8);  
            httppost.getParams().setParameter(HTTP.DEFAULT_PROTOCOL_CHARSET, HTTP.UTF_8);  
      
            // 设置参数  
             List<NameValuePair> params = new ArrayList<NameValuePair>();  
             params.add(new BasicNameValuePair("$xmldata", reqXml));  
             httppost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));   
//          StringEntity entity1 = new StringEntity(getUTF8XMLString(reqXml), "UTF-8");  
//          entity1.setContentType("text/xml;charset=UTF-8");  
//          entity1.setContentEncoding("UTF-8");  
//          httppost.setEntity(entity1);  
            //设置报文头  
            httppost.setHeader("Content-Type", "text/xml;charset=UTF-8");  
            // 发送请求  
            HttpResponse httpresponse = httpClient.execute(httppost);  
            // 获取返回数据  
            HttpEntity entity = httpresponse.getEntity();  
            body = EntityUtils.toString(entity);  
            if (entity != null) {  
                entity.consumeContent();  
            }  
        } catch (Exception e) {  
        	 throw new Exception(e);  
        }  
        return body;  
    }  
      
    /**
     *发送post请求
     * 
     * @author 陶召才
     * @Date 2016年4月14日  下午5:29:27
     * @Note <这里是使用注意事项>
     *
     * @param url
     * @param paramMap：参数
     * @return
     *
     * @return String
     */
	public static String post(String url,Map<String,String> paramMap){
    	StringBuffer responseStr = new StringBuffer();
    	
		HttpPost httpPost = null;
		HttpEntity he = null; 
		HttpClient hc = null;
		InputStream is  = null;
		BufferedReader br = null;
		try { 
			hc = new DefaultHttpClient();
			httpPost = new HttpPost(url);
			List<NameValuePair> params = new ArrayList<NameValuePair>();

			//以下几行代码可修改为map2pairs
	    	Iterator<?> it=paramMap.entrySet().iterator();
	    	while(it.hasNext()){//只遍历一次,速度快
	    		Map.Entry e=(Map.Entry)it.next();
	    		NameValuePair nameValuePair = new BasicNameValuePair((String)e.getKey(), (String)e.getValue());
	    		params.add(nameValuePair);
	    	}
	    
			he = new UrlEncodedFormEntity(params, "UTF-8");
			httpPost.setEntity(he); 
			
			HttpResponse ht = hc.execute(httpPost);
			
			//连接成功
			if(ht.getStatusLine().getStatusCode() == HttpStatus.SC_OK){ 	
				HttpEntity het = ht.getEntity();
			    is = het.getContent();
				br = new BufferedReader(new InputStreamReader(is,"UTF-8"));
				String readLine = null;
				while((readLine =br.readLine()) != null){ 
					responseStr.append(readLine);
				}
			}else{
				responseStr.append("0");//返回失败！
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}finally{
			if(is!=null)
				try {
					is.close();
				} catch (IOException e) {
					throw new RuntimeException(e);
				}
			if(br!=null)
				try {
					br.close();
				} catch (IOException e) {
					throw new RuntimeException(e);
				}
		}
		return responseStr.toString();
	}
	
	


	/**
	 * map转换为namevaluepair的列表
	 * @param message
	 * @return
	 */
	private List<NameValuePair> map2pairs(Map<String, String> message){
		List<NameValuePair> pairs = new ArrayList<NameValuePair>();
		if(null != message){
			for(Map.Entry<String, String> entry : message.entrySet()){
				pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
			}
		}
		return pairs;
	}
	
    
	
	
  
    public static void main(String[] args) {
    		
    		StringBuffer xmlStr = new StringBuffer();
    		xmlStr.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
    		.append("\n");
    		xmlStr.append("<Params>").append("\n");
    		xmlStr.append("  <InterfaceMode>IConsultationReg</InterfaceMode>")
    				.append("\n");
    		xmlStr.append("  <FuncCode>A100010</FuncCode>").append("\n");
    		xmlStr.append("  <DataList>").append("\n");
    		xmlStr.append("     <Name>张三</Name>").append("\n");
    		xmlStr.append("     <ID>777</ID>").append("\n");
    		xmlStr.append("    <Age>30</Age>").append("\n");
    		xmlStr.append("  </DataList>").append("\n");
    		xmlStr.append("</Params>").append("\n");
    		
    		
        	Map m = new HashMap();
        	m.put("xml", xmlStr.toString());
        	String ss = post("http://localhost:8080/successMainFrame/service.action",m);
        	System.out.println(ss);
    	
    
    	
    	}

	
}
